#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/9/16 20:54
# @Author  : herbert
# @File    : replace_file_content.py
# @Software: IntelliJ IDEA
import re
import os
import shutil
import xml.etree.ElementTree as ET


def add_module_to_file(sub_module_name, file_path):
    """
    向聚合pom文件中添加模块
    """
    mvn_ns = 'http://maven.apache.org/POM/4.0.0'
    # 定义命名空间映射
    ET.register_namespace('', uri=mvn_ns)
    # 加载pom.xml文件
    tree = ET.parse(file_path)
    root = tree.getroot()
    modules_element = root.find(f"{{{mvn_ns}}}modules")
    new_module = ET.Element('module')
    new_module.text = sub_module_name
    modules_element.append(new_module)
    tree.write(file_path)


def replace_file_contents(original_file_name, map_old_new):
    """
    替换文件中的文本
    """
    with open(original_file_name, 'r', encoding='utf-8') as file:
        content = file.read()
        for old_str, new_str in map_old_new.items():
            if old_str in content:
                content = content.replace(old_str, new_str)
    # 将新内容写回文件
    with open(original_file_name, 'w', encoding='utf-8') as file:
        file.write(content)
    print("done")


def copy_module_new(base_dir, new_module_number, new_module_name, old_module_number='ch00-ex00',
                    old_module_name='template'):
    """
    拷贝模板模块文件到新模块目录
    """
    # 定义源目录和目标目录
    new_module_dir = os.path.join(base_dir, new_module_number + '-' + new_module_name)
    old_module_dir = os.path.join(base_dir, old_module_number + '-' + old_module_name)

    # 文件
    # 旧应用名 Ch00Ex00TemplateApp.java
    old_app = ''.join([word.capitalize() for word in old_module_number.split('-') + old_module_name.split('-')]) + 'App'
    # 新应用名 Ch01Ex02LifeCircleApp.java
    new_app = ''.join([word.capitalize() for word in new_module_number.split('-') + new_module_name.split('-')]) + 'App'

    old_test_app = ''.join(
        [word.capitalize() for word in old_module_number.split('-') + old_module_name.split('-')]) + 'Test' + 'App'  #
    new_test_app = ''.join(
        [word.capitalize() for word in new_module_number.split('-') + new_module_name.split('-')]) + 'Test' + 'App'  #

    # 拷贝目录及文件
    shutil.copytree(old_module_dir, new_module_dir)

    for root, dirs, files in os.walk(new_module_dir):
        # 修改文件名
        # 文件名手写字母大写
        for file_name in files:
            old_file = os.path.join(root, file_name)
            new_file = old_file.replace(old_app, new_app)
            new_file = new_file.replace(old_test_app, new_test_app)
            os.rename(old_file, new_file)
    # 目录
    # 旧模块 ch00-ex00-template
    # 新模块 ch01-ex02-life-circle 都为中划线
    old_module_number_name = old_module_number + '-' + old_module_name
    new_module_number_name = new_module_number + '-' + new_module_name
    # 旧包名 ch00_ex00_template
    # 新包名 ch01_ex02_life_circle  都转为下划线
    old_package_name = old_module_number.replace('-', '_') + '_' + old_module_name.replace('-', '_')
    new_package_name = new_module_number.replace('-', '_') + '_' + new_module_name.replace('-', '_')
    for root, dirs, files in os.walk(new_module_dir):
        # 修改目录名
        for dir_name in dirs:
            old_dir = os.path.join(root, dir_name)
            new_dir = old_dir.replace(old_package_name, new_package_name)
            new_dir = new_dir.replace(old_module_dir, new_module_dir)
            os.rename(old_dir, new_dir)

    for root, dirs, files in os.walk(new_module_dir):
        # 修改文件内容
        for file_name in files:
            if file_name == 'pom.xml':
                # 修改artifact_id
                replace_file_contents(os.path.join(root, file_name), map_old_new={old_module_number_name: new_module_number_name})
            if file_name.endswith('.java'):
                replace_file_contents(original_file_name=os.path.join(root, file_name), map_old_new={old_app:new_app,old_test_app:new_test_app,old_package_name:new_package_name})
    # 将新的模块添加到聚合项目中
    add_module_to_file(new_module_number_name, os.path.join(base_dir, 'pom.xml'))


def split_number_name(number_and_name):
    """
    拆分模块和序号
    """
    pattern = r"(ch\d{2}-ex\d{2})-(.*)"
    match = re.search(pattern, number_and_name)
    if match:
        # 通过分组编号访问
        module_number = match.group(1)
        module_name = match.group(2)
        return module_number, module_name


def copy_module_list(base_dir, module_list):
    """
    批量复制模块
    """
    for item in module_list:
        result = split_number_name(item)
        if result is None:
            print("error: ", item)
        if result is not None:
            module_number, module_name = result
            copy_module_new(base_dir=base_dir, new_module_number=module_number, new_module_name=module_name)


if __name__ == '__main__':
    # 文件
    parent_dir = '/Users/vv/IdeaProjects/spring-boot-learning-2024'
    new_module_list1 = ['ch01-ex02-life-cycle', 'ch01-ex03-bean-processor', 'ch01-ex04-property-value',
                        'ch01-ex05-dependency-injection',
                        'ch02-ex01-aop', 'ch02-ex02-bean-factory-postprocessor', 'ch02-ex03-spring-init-source',
                        'ch02-ex04-servlet-v3']
    new_module_list2 = ['ch03-ex01-auto-config']
    new_module_list3 = ['ch31-ex01-spring-security']
    # for item in new_module_list:
    #     print(connect_module_str(item))
    copy_module_list(parent_dir, new_module_list3)
